import {Vector3} from "./Vector3";
import {Vector} from "./Vector";

export class InterpolateUtil {
    static barycentric(A: ArrayLike<number>, B: ArrayLike<number>, C:ArrayLike<number>, P:ArrayLike<number>): Vector3 {
        const s = [new Vector3(), new Vector3()];
        for (let i = 0; i<2; i++) {
            s[i].data[0] = C[i]  - A[i];
            s[i].data[1] = B[i]  - A[i];
            s[i].data[2] = A[i]  - P[i];
        }
        const u = Vector3.crossVector(s[0], s[1]);
        if (Math.abs(u.data[2]) > 1e-2) {
            return new Vector3(1-(u.x+u.y)/u.z, u.y/u.z, u.x/u.z);
        }
        return new Vector3(-1, 1, 1)
    }

    static interpolateVarying(a: any, b: any, c: any, v: Vector3) {
        if (a instanceof Vector) {
            // @ts-ignore
            const target = new a.constructor();
            for (let i=0; i<a.size; i++) {
                target.data[i] = a.data[i] * v.x + b.data[i] * v.y + c.data[i] * v.z;
            }
            return target;
        } else {
            return a*v.x +  b*v.y + c*v.z;
        }
    }

    static calcInterpolateLineP(m: number, m0: number, m1: number) {
        let p0: number, p1: number;
        if (m0 === m1) {
            p0 = 0.5;
            p1 = 0.5;
        } else {
            p0 = (m1- m) / (m1 - m0);
            p1 = (m - m0) / (m1 -m0);
        }
        return {p0, p1};
    }
    static interpolateLine<T>(m: number, m0: number, m1: number, v0: any, v1: any): T {
        let p0: number, p1: number;
        if (m0 === m1) {
            p0 = 0.5;
            p1 = 0.5;
        } else {
            p0 = (m1- m) / (m1 - m0);
            p1 = (m - m0) / (m1 -m0);
        }
        if (v0 instanceof Vector) {
            // @ts-ignore
            const target = new v0.constructor();
            for (let i=0; i<target.size; i++) {
                target.data[i] = v0.data[i] * p0 + v1.data[i] * p1;
            }
            return target;
        } else {
            // @ts-ignore
            return v0 * p0 + v1 * p1;
        }
    }


}